package independence.reflection
{
	import flash.system.ApplicationDomain;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import independence.core.IndyObject;
	
	/**
	 * The <code>ClassLoader</code> class provides several static methods for working with classes,
	 * such as methods for getting a class by its qualified name and getting the class of a target
	 * object. It wraps Flash Player errors in more specific Independence errors, allowing the developer
	 * to much more easily understand the problems with his code. 
	 * 
	 * @see	independence.reflection.ClassNotFoundError
	 * @author	TK, TK Assembled for Independence Glory.
	 */
	public class ClassLoader extends IndyObject
	{
		/**
		 * Returns a class by its fully-qualified class name. 
		 * @param	name	The fully-qualified class name to search for.
		 * @throws	independence.reflection.ClassNotFoundError	If the requested class cannot be found, a <code>ClassNotFoundError</code> is thrown.
		 */
		public static function forName(name:String, applicationDomain:ApplicationDomain = null):Class
		{
			if (applicationDomain == null) {
				try {
					return getDefinitionByName(name) as Class;
				} catch (e:Error) {
					throw new ClassNotFoundError(name);
					return null;
				}
			} else {
				if (applicationDomain.hasDefinition(name)) {
					return applicationDomain.getDefinition(name) as Class;
				} else {
					throw new ClassNotFoundError(name);
					return null;
				}
			}
			return null;
		}
		/**
		 * Returns the <code>Class</code> of an input object. If the object is itself a <code>Class</code>,
		 * it returns it. 
		 * @param	target	The object to retrieve the class of. 
		 */
		public static function getClass(target:Object):Class
		{
			try {
				return (getDefinitionByName(getQualifiedClassName(target)) as Class);
			} catch (e:Error) {
				throw new ClassNotFoundError(getQualifiedClassName(target));
				return null;
			}
			return null;
		}
	}
}